package com.example.programmatic;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @description: 编程式事务
 * @author: lzp
 * @createTime: 2021-11-21 15:00
 **/
@SpringBootApplication
@Slf4j
public class Application implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TransactionTemplate transactionTemplate; // 事务模板

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("事务开始之前：{}", getCount());
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                jdbcTemplate.execute("INSERT INTO FOO(BAR) VALUES('编程式事务')");
                log.info("事务中计数：{}", getCount());
//                status.setRollbackOnly(); // 回滚
                status.isCompleted();
            }
        });
        log.info("事务开始之后：{}", getCount());
    }

    private long getCount() {
        return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM FOO", Long.class);
    }
}
